package com.gitee.grower.util.germ

import com.germ.germplugin.api.dynamic.gui.GermGuiCanvas
import com.germ.germplugin.api.dynamic.gui.GermGuiLayout
import com.germ.germplugin.api.dynamic.gui.GermGuiPart
import com.germ.germplugin.api.dynamic.gui.GermGuiScroll
import com.gitee.grower.util.germ.germ.GermPartDSL
import taboolib.library.configuration.ConfigurationSection

class GermCanvasDSL : GermPartDSL<GermGuiCanvas>() {

    var invalid = false

    var width = ""
    var height = ""

    var layout: Layout? = null

    var parts = mutableListOf<GermPartDSL<*>>()

    override val type: String = "canvas"


    override fun infuse(config: ConfigurationSection) {
        name = config.name

        config.getString("locationX")?.let { locationX = it }
        config.getString("locationY")?.let { locationY = it }
        config.getString("locationZ")?.let { locationZ = it }
        config.getString("width")?.let { width = it }
        config.getString("height")?.let { height = it }
        config.getConfigurationSection("layout")?.let {
            layout = Layout(
                config.getString("layout.type")!!,
                config.getString("layout.gapX")!!,
                config.getString("layout.gapY")!!
            )
        }

        config.getConfigurationSection("scrollableParts")?.getKeys(false)?.forEach {
            parts += createDSL<GermPartDSL<*>>(config.getConfigurationSection("scrollableParts.$it")!!)
        }

        invalid = config.getBoolean("invalid")

        enable = config.getBoolean("enable")
    }

    class Layout(val type: String, val gapX: String, val gapY: String) {

        fun create(): GermGuiLayout {
            return GermGuiLayout().also {
                it.gapY = gapY
                it.gapX = gapX
                it.type = type
            }
        }

    }

    override fun create(): GermGuiCanvas {
        return GermGuiCanvas(name).also {

            it.locationX = locationX
            it.locationY = locationY
            it.locationZ = locationZ
            it.enable = enable
            it.isInvalid = invalid

            it.width = width
            it.height = height
            layout?.apply {
                it.setLayout(layout!!.create())
            }

            parts.map { it.create() as GermGuiPart<*> }.forEach(it::addGuiPart)

        }
    }


}